package com.hxut.servlet;

import com.hxut.dao.GoodsDao;
import com.hxut.dao.ShoppingCart;
import com.hxut.model.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "AddGoodsToCartServlet",urlPatterns = "/addGoodsToCartServlet")
public class AddGoodsToCartServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = Integer.parseInt(req.getParameter("id"));
        //根据id查询产品信息
        GoodsDao goodsDao = new GoodsDao();
        Goods goods = goodsDao.findGoodsById(id);
        HttpSession session = req.getSession();
        if (goods!=null){ //产品不为空，才存到购物车
            ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
            if (cart==null){//创建一个购物车
                cart = new ShoppingCart();
            }
            cart.AddProduct(goods);
            //存入新的购物车
            session.setAttribute("cart",cart);
        }
        //重定向到查询产品信息
        resp.sendRedirect(req.getContextPath()+"/goodsListPageServlet");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
